package com.smart.community.user.service.impl;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.smart.community.user.service.CacheService;

import lombok.extern.slf4j.Slf4j;

/**
 * 缓存服务实现
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Slf4j
@Service
public class CacheServiceImpl implements CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void set(String key, Object value, long expireTime) throws Exception {
        try {
            redisTemplate.opsForValue().set(key, value, Duration.ofSeconds(expireTime));
            log.debug("缓存设置成功，键：{}，过期时间：{}秒", key, expireTime);
        } catch (Exception e) {
            log.error("缓存设置失败，键：{}", key, e);
            throw new Exception("缓存设置失败：" + e.getMessage());
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> clazz) throws Exception {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            if (value != null) {
                log.debug("缓存获取成功，键：{}", key);
                return (T) value;
            }
            log.debug("缓存未命中，键：{}", key);
            return null;
        } catch (Exception e) {
            log.error("缓存获取失败，键：{}", key, e);
            throw new Exception("缓存获取失败：" + e.getMessage());
        }
    }

    @Override
    public void delete(String key) throws Exception {
        try {
            Boolean result = redisTemplate.delete(key);
            if (Boolean.TRUE.equals(result)) {
                log.debug("缓存删除成功，键：{}", key);
            } else {
                log.debug("缓存删除失败，键不存在：{}", key);
            }
        } catch (Exception e) {
            log.error("缓存删除失败，键：{}", key, e);
            throw new Exception("缓存删除失败：" + e.getMessage());
        }
    }

    @Override
    public boolean exists(String key) throws Exception {
        try {
            Boolean result = redisTemplate.hasKey(key);
            boolean exists = Boolean.TRUE.equals(result);
            log.debug("缓存存在检查，键：{}，结果：{}", key, exists);
            return exists;
        } catch (Exception e) {
            log.error("缓存存在检查失败，键：{}", key, e);
            throw new Exception("缓存存在检查失败：" + e.getMessage());
        }
    }
} 